package com.moorror.cola.strategy.plugin.utils;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.google.common.collect.Maps;

import java.util.Map;

/**
 * @Author jiyanghuang
 * @Date 2022/3/21 4:29 PM
 * 如果是某个类不存在时，加载失败，此时使用该工具来付出全类名
 */
public class AnnotationClassNameHolderUtils {

    private final static ThreadLocal<Map<String, Map<String,String>>> threadLocal = new TransmittableThreadLocal<>();

    /**
     * {"class":{"fieldKey","value"}}
     * @param clazzFieldValue
     */
    public static void save(Map<String, Map<String,String>> clazzFieldValue) {
        threadLocal.set(clazzFieldValue);
    }

    /**
     * 该值一定是先填充，然后再调用
     * 因此不判断空处理
     *
     * @return
     */
    public static Map<String, Map<String,String>> find() {
        return threadLocal.get();
    }

    public static void remove() {
        threadLocal.remove();
    }

    public static void remove(String superClassName) {
        Map<String, Map<String, String>> clazzFieldValue = find();
        if (null == clazzFieldValue) {
            remove();
            return;
        }
        Map<String, String> fieldValue = clazzFieldValue.get(superClassName);
        if (null != fieldValue) {
            clazzFieldValue.remove(superClassName);
        }
        if(clazzFieldValue.size() <= 0){
            remove();
        }
    }

    public static String value(String superClassName, String fieldName) {
        Map<String, Map<String, String>> clazzFieldValue = find();
        if (null == clazzFieldValue) {
            return "";
        }
        Map<String, String> fieldValue = clazzFieldValue.get(superClassName);
        if (null == fieldValue) {
            return "";
        }
        return fieldValue.get(fieldName);
    }

    public static void putValue(String superClassName, String fieldName, String value) {
        Map<String, Map<String, String>> clazzFieldValue = find();
        if (null == clazzFieldValue) {
            clazzFieldValue = Maps.newHashMap();
            save(clazzFieldValue);
        }
        Map<String, String> fieldValue = clazzFieldValue.get(superClassName);
        if (null == fieldValue) {
            fieldValue = Maps.newHashMap();
            clazzFieldValue.put(superClassName, fieldValue);
        }
        fieldValue.put(fieldName, value);
    }
}
